/**
 * @file router 配置
 * @author Mybatis_shixi_Team
 */

import Vue from 'vue'
import VueRouter from 'vue-router'

import store from '@/store'
import http from '@/api'
import preload from '@/common/preload'
import { Message } from 'element-ui'

Vue.use(VueRouter)

// const MainEntry = () => import(/* webpackChunkName: 'entry' */'@/views')
const NotFound = () => import(/* webpackChunkName: 'none' */'@/views/404')

const routes = [
    {
        path: '/login',
        name: 'login',
        alias: '',
        meta: {
            isRequired: false,
            Member: false // 会员才能浏览的页面为true
        },
        component: () => import(/* webpackChunkName: 'login' */'@/views/login/index')
    },
    {
        path: '/register',
        name: 'register',
        meta: {
            isRequired: false
        },
        component: () => import(/* webpackChunkName: 'login' */'@/views/register/index')
    },
    {
        path: '',
        name: 'appMain',
        component: () => import(/* webpackChunkName: 'home' */'@/views/home'),
        meta: {
            isRequired: false,
            Member: false
        },
        children: [
            {
                path: '/findpassword',
                name: 'findpassword',
                component: () => import(/* webpackChunkName: 'order' */'@/views/findpassword'),
                meta: {
                    isRequired: false,
                    Member: false
                }
            },
            {
                path: '/register',
                name: 'register',
                component: () => import(/* webpackChunkName: 'order' */'@/views/register'),
                meta: {
                    isRequired: false,
                    Member: false
                }
            },
            {
                path: 'commodity',
                name: 'commodity',
                component: () => import(/* webpackChunkName: 'commodity' */'@/views/commodity'),
                meta: {
                    isRequired: true
                }
            },
            {
                path: 'addCommodity',
                name: 'addCommodity',
                component: () => import(/* webpackChunkName: 'commodity' */'@/views/commodity/addCommodity'),
                meta: {
                    isRequired: true
                }
            },
            {
                path: 'shoppingTrolley',
                name: 'shoppingTrolley',
                component: () => import(/* webpackChunkName: 'commodity' */'@/views/shoppingTrolley'),
                meta: {
                    isRequired: true
                }
            },
            {
                path: 'order',
                name: 'order',
                component: () => import(/* webpackChunkName: 'order' */'@/views/order'),
                meta: {
                    isRequired: true
                }
            },
            {
                path: 'customerorder',
                name: 'customerorder',
                component: () => import(/* webpackChunkName: 'order' */'@/views/order/CustomerOrder.vue'),
                meta: {
                    isRequired: true
                }
            },
            {
                path: 'customerorderdetail',
                name: 'customerorderdetail',
                component: () => import(/* webpackChunkName: 'order' */'@/views/order/CustomerOrderDetail.vue'),
                meta: {
                    isRequired: true
                }
            },
            {
                path: 'orderdetail',
                name: 'orderdetail',
                component: () => import(/* webpackChunkName: 'order' */'@/views/order/orderdetail.vue'),
                meta: {
                    isRequired: true
                }
            },
            {
                path: '/personal',
                name: 'personal',
                component: () => import(/* webpackChunkName: 'order' */'@/views/personal'),
                meta: {
                    isRequired: true
                }
            }
        ]
    },
    // 404
    {
        path: '*',
        name: '404',
        component: NotFound
    }
]

const router = new VueRouter({
    mode: 'history',
    routes: routes
})

const cancelRequest = async () => {
    const allRequest = http.queue.get()
    const requestQueue = allRequest.filter(request => request.cancelWhenRouteChange)
    await http.cancel(requestQueue.map(request => request.requestId))
}

let preloading = true
let canceling = true
let pageMethodExecuting = true

router.beforeEach(async (to, from, next) => {
    canceling = true
    await cancelRequest()
    canceling = false
    // 判断是否登录，若没有登录则跳转至登录界面
    if (to.meta.isRequired) {
        if (sessionStorage.getItem('user')) {
            next()
        } else {
            Message.warning({
                message: '你还未登录，请先登录'
            })
            next({
                path: '/login'
            })
        }
    } else {
        next()
    }

    if (to.meta.Member === true) {
        if (JSON.parse(sessionStorage.getItem('user')).member === true) {
            next()
        } else {
            Message.warning({
                message: '认证成为会员,方可解锁'
            })
            next({
                path: '/personal'
            })
        }
    } else {
        next()
    }
})

router.afterEach(async (to, from) => {
    store.commit('setMainContentLoading', true)

    preloading = true
    await preload()
    preloading = false

    const pageDataMethods = []
    const routerList = to.matched
    routerList.forEach(r => {
        Object.values(r.instances).forEach(vm => {
            if (typeof vm.fetchPageData === 'function') {
                pageDataMethods.push(vm.fetchPageData())
            }
            if (typeof vm.$options.preload === 'function') {
                pageDataMethods.push(vm.$options.preload.call(vm))
            }
        })
    })

    pageMethodExecuting = true
    await Promise.all(pageDataMethods)
    pageMethodExecuting = false

    if (!preloading && !canceling && !pageMethodExecuting) {
        store.commit('setMainContentLoading', false)
    }
})

export default router
